<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="C++的继承与多态接口继承与实现继承派生类将基类中除去构造函数和析构函数的其他方法继承了过来。public继承概念由两部分组成，函数接口(function interfaces)继承和函数实现(function implementations)继承。作为类的开发人员，我们主要研究类的三种继承情况：1、派生类只继承成员函数的接口(也就是声明)，需要自己来重新定义该函数的实现；2、派生类同时继承函数的">
<meta property="og:type" content="article">
<meta property="og:title" content="深入探究C++">
<meta property="og:url" content="http://example.com/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="C++的继承与多态接口继承与实现继承派生类将基类中除去构造函数和析构函数的其他方法继承了过来。public继承概念由两部分组成，函数接口(function interfaces)继承和函数实现(function implementations)继承。作为类的开发人员，我们主要研究类的三种继承情况：1、派生类只继承成员函数的接口(也就是声明)，需要自己来重新定义该函数的实现；2、派生类同时继承函数的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-06T12:27:42.000Z">
<meta property="article:modified_time" content="2021-11-03T08:18:26.702Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="C++初学">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入探究C++ | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入探究C++
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2020-09-06 20:27:42" itemprop="dateCreated datePublished" datetime="2020-09-06T20:27:42+08:00">2020-09-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:18:26" itemprop="dateModified" datetime="2021-11-03T16:18:26+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index"><span itemprop="name">C++</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="C-的继承与多态"><a href="#C-的继承与多态" class="headerlink" title="C++的继承与多态"></a>C++的继承与多态</h1><h2 id="接口继承与实现继承"><a href="#接口继承与实现继承" class="headerlink" title="接口继承与实现继承"></a>接口继承与实现继承</h2><p>派生类将基类中除去构造函数和析构函数的其他方法继承了过来。public继承概念由两部分组成，函数接口(function interfaces)继承和函数实现(function implementations)继承。作为类的开发人员，我们主要研究类的三种继承情况：<br>1、派生类只继承成员函数的接口(也就是声明)，需要自己来重新定义该函数的实现；<br>2、派生类同时继承函数的接口和实现，但又希望能够覆写(override)它们所继承的实现；<br>3、派生类同时继承函数的接口和实现，并且不允许覆盖任何东西，只能利用父函数的实现；</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Shape</span>&#123;</span><span class="comment">//形状</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">draw</span><span class="params">()</span> <span class="keyword">const</span> </span>= <span class="number">0</span>;</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">error</span><span class="params">(<span class="keyword">const</span> <span class="built_in">std</span>::<span class="built_in">string</span>&amp; msg)</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">objectID</span><span class="params">()</span> <span class="keyword">const</span></span>;</span><br><span class="line">  ...</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Rectangle</span>:</span><span class="keyword">public</span> Shape&#123;...&#125;;<span class="comment">//矩形</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ellipse</span>:</span><span class="keyword">public</span> Shape&#123;...&#125;;<span class="comment">//椭圆</span></span><br></pre></td></tr></table></figure>

<p>Shape是个抽象类，它的纯虚函数draw使它成为一个抽象类，所以客户不能够创建Shape class的实体，只能创建它的派生类的实体</p>
<p>Shape类声明了三个函数，第一个是draw，在视屏中划出当前对象，第二个是error，准备让那些“需要报导某个错误”的成员函数调用，第三个是objectID，返回当前对象的独一无二的整数识别码，每个函数的声明方式都不相同，draw是个纯虚函数(pure virtual)，error是个虚函数( 简朴的(非纯)impure virtual函数)，objectID是个非虚函数(non-virtual)函数。</p>
<p>纯虚函数通常有两个特点：它们必须被任何“继承了他们”的具象类重新声明；并且它们在抽象类中通常没有定义。<br>所以结论是：声明一个纯虚函数的目的是为了让派生类只继承函数的接口。</p>
<p>虚函数（简朴的impure virtual函数）背后的故事和纯虚函数（pure virtual函数）有点不同，一如往常，派生类继承其函数接口，但虚函数（简朴的impure virtual函数）会提供一份实现代码，派生类可能覆写（override）它，所以结论是：</p>
<p>声明虚函数（简朴的impure virtual函数）的目的是让派生类继承该函数的接口和缺省实现，考虑error函数，其接口表示，每个类都必须支持一个“当遇上错误是可调用”的函数，但每个类可自由处理错误，若某个类不想针对错误做出任何特殊行为，它可以退回到Shape类提供的缺省错误处理行为。但是允许虚函数（简朴的impure virtual函数）同时指定函数声明和函数缺省行为，却有可能造成危险，考虑下面的例子：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//XYZ航空公司的飞机继承体系，该公司只有A型和B型两种飞机，两者都以相同方式飞行，因此XYZ设计的继承体系为：</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Airport</span>&#123;</span>...&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Airplane</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span> :</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span>;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Airplane::fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span></span><br><span class="line"><span class="function"></span>&#123;  </span><br><span class="line">  <span class="comment">//缺省代码，将飞机飞至指定的目的地</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelA</span>:</span><span class="keyword">public</span> Airplane&#123;...&#125;;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelB</span>:</span><span class="keyword">public</span> Airplane&#123;...&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//现在，新增加一个C型飞机，C型和A型、B型的飞行方式不同，XYZ公司的程序员在继承体系中针对C型飞机加了一个类，但由于急于让飞机上线，竟然忘了定义其fly函数：</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelC</span>:</span><span class="keyword">public</span> Airplane&#123;</span><br><span class="line">    ...  <span class="comment">//为声明fly函数</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>若代码中出现如下操作：<br>Airport PDX(…);//PDX是机场名字<br>Airplane* pa = new ModelC;<br>…<br>pa-&gt;fly(PDX);//调用Airplane::fly</p>
<p>这将酿成大祸，这个程序试图以ModelA或ModelB的飞行方式来飞ModelC。解决该问题的要点在于切断“虚函数接口”和其“缺省实现”之间的连接，下面是一种做法：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Airplane</span>&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">fly</span><span class="params">(<span class="keyword">const</span> Airplane&amp; destination)</span> </span>= <span class="number">0</span>;</span><br><span class="line">  ...</span><br><span class="line"><span class="keyword">protected</span>:</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">defaultFly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Airplane::defaultFly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"> <span class="comment">// 缺省行为，将飞机飞至指定的目的地</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//现在ModelA和ModelB调用的飞行的缺省实现为：</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelA</span>:</span><span class="keyword">public</span> Airplane&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">    defaultFly(destination);</span><br><span class="line">    ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelB</span>:</span><span class="keyword">public</span> Airplane&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">    defaultFly(destination);</span><br><span class="line">    ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//现在ModelC class 不可能意外继承不正确的fly实现代码，因为Airplane中的纯虚函数迫使ModelC必须提供自己的fly版本：</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelC</span>:</span><span class="keyword">public</span> Airplane&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span>;</span><br><span class="line">  &#123;</span><br><span class="line">    ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">ModelC::fly</span><span class="params">(<span class="keyword">const</span> Airport&amp; destination)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="comment">//将C型飞机飞至指定目的地</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后考虑Shape的非虚函数objectID()。若成员函数是个非虚函数，意味着它并不打算在派生类中有不同的行为，实际上非虚成员函数所表现的不变性远重要于特异性，因为它表示不论派生类变得多么特异化，就其自身而言，它的行为都不可以改变。</p>
<p>1、接口继承和实现继承不同。在public继承之下，派生类总是继承基类的接口；</p>
<p>2、纯虚函数只是具体指定接口继承；</p>
<p>3、虚函数( 简朴的（非纯）impure virtual函数)具体指定接口继承及缺省实现继承；</p>
<p>4、非虚函数(non-virtual函数)具体指定接口继承以及强制性实现继承。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>接口继承：派生类只继承函数的接口</p>
<p>实现继承：派生类同时继承函数的接口和实现</p>
<p>虚函数是重载的一种表现方式，是一种动态的重载方式。</p>
<p>非虚函数：继承该函数的接口和一份强制性实现，继承类必须含有某个接口，必须使用基类的实现</p>
<p>虚函数：会继承该函数的接口和缺省实现。继承类必须含有某个接口，可以自己实现，也可以不实现，而采用基类定义的缺省实现。</p>
<p>纯虚函数：纯虚函数在基类中没有定义，接口继承。含有纯虚函数的类无法实例化。要求继承类必须含有某个接口，并对接口函数实现。</p>
<h2 id="多态与继承"><a href="#多态与继承" class="headerlink" title="多态与继承"></a>多态与继承</h2><h3 id="继承访问修饰符"><a href="#继承访问修饰符" class="headerlink" title="继承访问修饰符"></a>继承访问修饰符</h3><p>继承方式有三种——public、protected和private，不同的继承方式对继承到派生类中的基类成员有什么影响？ 总的来说，父类成员的访问限定符通过继承派生到子类中之后，访问限定符的权限小于、等于原权限。其中，父类中的private成员只有父类本身及其友元可以访问，通过其他方式都不能进行访问，当然就包括继承。protected多用于继承当中，如果对父类成员的要求是——子类可访问而外部不可访问，则可以选择protected继承方式。</p>
<h3 id="父子类中同名元素"><a href="#父子类中同名元素" class="headerlink" title="父子类中同名元素"></a>父子类中同名元素</h3><h4 id="overload重载"><a href="#overload重载" class="headerlink" title="overload重载"></a>overload重载</h4><p>函数重载有三个条件，一函数名相同，二形参类型、个数、顺序不同，三相同作用域。根据第三个条件，可知函数重载只可能发生在一个类中</p>
<h4 id="overhide隐藏"><a href="#overhide隐藏" class="headerlink" title="overhide隐藏"></a>overhide隐藏</h4><p>在派生类中将基类中的同名成员方法隐藏，要想在派生类对象中访问基类同名成员得加上基类作用域。(注意，如果该同名方法在基类中实现了重载，在派生类对象中同样需要指定作用域，而不能通过简单的传参，调用带参重载方法)</p>
<h4 id="override函数覆盖"><a href="#override函数覆盖" class="headerlink" title="override函数覆盖"></a>override函数覆盖</h4><p>基类、派生类中的同名方法 函数头相同(参数、返回值)，且基类中该方法为虚函数，则派生类中的同名方法将基类中方法覆盖。函数隐藏和函数覆盖都是发生在基类和派生类之间的，可以这么理解：基类和派生类中的同名函数，除去是覆盖的情况，其他都是隐藏的情况。</p>
<h3 id="引用与指针"><a href="#引用与指针" class="headerlink" title="引用与指针"></a>引用与指针</h3><h4 id="基类对象和派生类对象"><a href="#基类对象和派生类对象" class="headerlink" title=". 基类对象和派生类对象"></a>. 基类对象和派生类对象</h4><p>派生类对象可以赋值给基类对象，基类对象不可以赋值给基类对象；对于基类对象和派生类对象，编译器默认支持从下到上的转换，上是基类，下是派生类。</p>
<h4 id="基类指针-引用-和派生类指针-引用"><a href="#基类指针-引用-和派生类指针-引用" class="headerlink" title="基类指针(引用)和派生类指针(引用)"></a>基类指针(引用)和派生类指针(引用)</h4><p>基类指针(引用)可以指向派生类对象，但只能访问派生类中基类部分的方法，不能访问派生类部分方法。派生类指针(引用)不可以指向基类对象，解引用可能出错，因为派生类的一些方法可能基类没有。</p>
<h3 id="虚函数"><a href="#虚函数" class="headerlink" title="虚函数"></a>虚函数</h3><p>分析：当Base类中有虚函数时，不论是Base类还是Derive类，它们的大小都增加了4个字节。并且当Base<em>指向Derive对象时，</em>Base的类型却变为Derive，不再和指针本身的类型相关，这是怎么回事呢？</p>
<h4 id="虚函数指针"><a href="#虚函数指针" class="headerlink" title="虚函数指针"></a>虚函数指针</h4><p>  实际上，Base和Derive类增加的4个字节就是虚函数指针的大小，每一个类只要有虚函数(包括继承而来的)，它就有且只有一个虚函数指针，类的大小就是总的成员变量的大小加上一个虚函数指针的大小。虚函数指针指向的是一张虚表，里面是这个类所有虚函数的地址，一个类对应一张虚函数表，而虚函数指针存在于每一个对象中，并且永远占据对象内存的前四个字节。</p>
<p>虚函数表又称为“虚表”，它在编译期间就已经确定，在程序运行时就会被装载到只读数据段，在整个程序运行期间都会一直存在。一个类实例化的多个对象，它们 的虚函数指针指向的是同一张虚表。</p>
<h4 id="虚函数要求"><a href="#虚函数要求" class="headerlink" title="虚函数要求"></a>虚函数要求</h4><p>成员函数能实现为虚函数需要满足两个前提条件： 1.成员方法能取地址  2.成员方法依赖于对象。第一点毋庸置疑，虚函数表中需要存储虚函数的地址。第二点，我们怎么调用虚函数的？通过虚函数指针来找到虚表从而调用其中的方法，而虚函数指针又存在于对象中，所以这就意味着虚函数的调用需要依赖对象。</p>
<p>  那么，我们可以确定一些不能实现为虚函数的方法： 1.构造函数——构造函数就是用来创建对象的，如何将其实现为虚函数，使其依赖一个对象调用？ 2.inline函数——内联函数直接在调用点展开，不能取地址 3.static方法——静态方法是属于整个类的，不依赖与单个对象。</p>
<p>成员函数能实现为虚函数需要满足两个前提条件： 1.成员方法能取地址  2.成员方法依赖于对象。第一点毋庸置疑，虚函数表中需要存储虚函数的地址。第二点，我们怎么调用虚函数的？通过虚函数指针来找到虚表从而调用其中的方法，而虚函数指针又存在于对象中，所以这就意味着虚函数的调用需要依赖对象。</p>
<p>  前面我们探讨了那些不能实现虚函数的情况，析构函数是可以的。那么什么时候应该将析构函数实现为虚函数呢？答案是：当基类指针指向堆上开辟的派生类对象时。</p>
<p>静态绑定发生在编译阶段、动态绑定发生在运行阶段。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/" title="深入探究C++">http://example.com/2020/09/06/C++/深入探究C/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/C-%E5%88%9D%E5%AD%A6/" rel="tag"># C++初学</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/06/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%AE%97%E6%B3%95/" rel="prev" title="二叉树算法">
      <i class="fa fa-chevron-left"></i> 二叉树算法
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/06/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript/" rel="next" title="深入探究JavaScript">
      深入探究JavaScript <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#C-的继承与多态"><span class="nav-number">1.</span> <span class="nav-text">C++的继承与多态</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#接口继承与实现继承"><span class="nav-number">1.1.</span> <span class="nav-text">接口继承与实现继承</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">1.1.1.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多态与继承"><span class="nav-number">1.2.</span> <span class="nav-text">多态与继承</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#继承访问修饰符"><span class="nav-number">1.2.1.</span> <span class="nav-text">继承访问修饰符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#父子类中同名元素"><span class="nav-number">1.2.2.</span> <span class="nav-text">父子类中同名元素</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#overload重载"><span class="nav-number">1.2.2.1.</span> <span class="nav-text">overload重载</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#overhide隐藏"><span class="nav-number">1.2.2.2.</span> <span class="nav-text">overhide隐藏</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#override函数覆盖"><span class="nav-number">1.2.2.3.</span> <span class="nav-text">override函数覆盖</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引用与指针"><span class="nav-number">1.2.3.</span> <span class="nav-text">引用与指针</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基类对象和派生类对象"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">. 基类对象和派生类对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#基类指针-引用-和派生类指针-引用"><span class="nav-number">1.2.3.2.</span> <span class="nav-text">基类指针(引用)和派生类指针(引用)</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#虚函数"><span class="nav-number">1.2.4.</span> <span class="nav-text">虚函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#虚函数指针"><span class="nav-number">1.2.4.1.</span> <span class="nav-text">虚函数指针</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#虚函数要求"><span class="nav-number">1.2.4.2.</span> <span class="nav-text">虚函数要求</span></a></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

